package com.tools.common.auth.util;

import com.tools.cache.util.RedisUtils;
import com.tools.common.auth.annotation.RequiresPermissions;
import com.tools.common.auth.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;

import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.List;

import static java.util.stream.Collectors.toList;

/**
 * @Description
 * @Author 小柒2012
 * @Date 2020/6/12
 */
@Component
public class AuthUtils {

    @Autowired
    private RedisUtils redisUtils;

    public boolean check(Object handler,String userId){
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Annotation permAnnotation= handlerMethod.getMethod().getAnnotation(RequiresPermissions.class);
        if(permAnnotation!=null) {
            String[] role = handlerMethod.getMethod().getAnnotation(RequiresPermissions.class).value();
            List<String> roleList = Arrays.asList(role);
            /**
             * 获取用户实际权限
             */
            List<Object> list = redisUtils.lGet("perms:"+userId,0,-1);
            List<String> permissions = roleList.stream().filter(item -> list.contains(item)).collect(toList());
            if (permissions.size() == 0) {
                return false;
            }
        }else{
            Annotation roleAnnotation= handlerMethod.getMethod().getAnnotation(RequiresRoles.class);
            if(roleAnnotation!=null){
                String[] role = handlerMethod.getMethod().getAnnotation(RequiresRoles.class).value();
                List<String> roleList = Arrays.asList(role);
                /**
                 * 获取用户实际角色
                 */
                List<Object> list = redisUtils.lGet("roles:"+userId,0,-1);
                List<String> roles = roleList.stream().filter(item -> list.contains(item)).collect(toList());
                if (roles.size() == 0) {
                    return false;
                }
            }
        }
        return true;
    }
}
